package com.allwees.core.event.annotation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class LocalEventAnnotationParser implements Serializable {

    @Nullable
    public Collection<LocalEventOperation> parseCacheAnnotations(Method method) {

        Collection<LocalEventOperation> ops = new ArrayList<>(5);

        LocalEvent localEvent = method.getAnnotation(LocalEvent.class);
        LocalEvents localEvents = method.getAnnotation(LocalEvents.class);

        if (localEvent != null) {
            ops.add(parseLocalEventAnnotation(localEvent));
        }
        if (localEvents != null) {
            ops.addAll(parseLocalEventAnnotation(localEvents));
        }
        return ops;
    }

    private List<LocalEventOperation> parseLocalEventAnnotation(LocalEvents events) {
        if (events == null || events.events().length == 0) {
            return new ArrayList<>();
        }
        List<LocalEventOperation> ops = new ArrayList<>(events.events().length);
        for (LocalEvent event : events.events()) {
            ops.add(parseLocalEventAnnotation(event));
        }
        return ops;
    }

    private LocalEventOperation parseLocalEventAnnotation(LocalEvent localEvent) {

        LocalEventOperation.Builder builder = new LocalEventOperation.Builder();

        builder.setCondition(localEvent.condition());
        builder.setSource(localEvent.source());
        builder.setEvent(localEvent.event());
        return builder.build();
    }
}
